
package com.kingdee.eas.custom.aoyuan.aytime.bizbill.web;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.AbortProcessingException;

import org.apache.commons.lang.StringUtils;
import org.operamasks.faces.annotation.Accessible;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.component.action.ActionEvent;
import org.operamasks.faces.component.form.impl.UIDateField;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.dao.AbstractBaseObjectCollection;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.query.IQueryExecutor;
import com.kingdee.bos.dao.query.QueryExecutorFactory;
import com.kingdee.bos.metadata.IMetaDataPK;
import com.kingdee.bos.metadata.MetaDataPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.waf.action.AbstractWebAction;
import com.kingdee.bos.waf.annotation.IBOSBizCtrl;
import com.kingdee.bos.waf.ctx.WafContext;
import com.kingdee.bos.waf.winlet.BaseBean;
import com.kingdee.bos.waf.winlet.list.ListBean;
import com.kingdee.bos.web.components.widget.impl.UIPromptBox;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.framework.ICoreBase;
import com.kingdee.eas.framework.util.FilterUtility;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.AdminOrgUnitInfo;
import com.kingdee.eas.basedata.org.FullOrgUnitInfo;
import com.kingdee.eas.basedata.org.HROrgUnitInfo;
import com.kingdee.eas.basedata.org.PositionInfo;
import com.kingdee.eas.basedata.org.PositionMemberCollection;
import com.kingdee.eas.basedata.org.PositionMemberFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.aoyuan.aytime.ManagerWebUtil;
import com.kingdee.eas.custom.aoyuan.aytime.bizbill.HolidayBillEntryFactory;
import com.kingdee.jdbc.rowset.IRowSet;


@ManagedBean(name = "custom.aoyuan.aytime.bizbill.AttenDetailListUIBean", scope = ManagedBeanScope.SESSION)
public class AttenDetailListUIBean extends AbstractAttenDetailListUIBean {

	
	   public AttenDetailListUIBean()
	    {
	    	displayRows = 20;  	
	    }
	   
		protected void actionQueryData_actionPerformed(ActionEvent event) throws AbortProcessingException {
			queryEntityViewInfo();
			super.refresh();
			if(this.pagedListData.getTotalCount()==0)
			{
	    		addMessage("没有找到员工考勤记录!");		
			}
		}
	   
	    @Bind(id="prmtDept")
	    private UIPromptBox prmtDept;
	    
	    @Bind
	    private String showHeight;
	    
	    @Bind
	    private String empId="";
	    
	    @Bind
	    private int displayRows;

	    @Bind
	    private UIDateField pkstartDate;
	    
	    @Bind
	    private UIDateField pkendDate;
	    
	    @Bind
	    private FullOrgUnitInfo dept;
	    
	    @Bind
	    private boolean isManager=false;
	    
	    public void pageOnload()
	    {	
	    	setEntityViewInfoOnload();
	    	super.pageOnload();
	    	initShowHeight();  
	    	PersonInfo personInfo =ContextUtil.getCurrentUserInfo(WafContext.getInstance().getContext()).getPerson();
	    	if(personInfo!=null)
	    	{
	    		empId=personInfo.getId().toString();
	    	}
	    	if(isManager)
	    	{
	    		prmtDept.setDisabled(false);
	    	}else
	    	{
	    		prmtDept.setDisabled(true);	    		
	    	}
	    }
	    
	    public void setEntityViewInfoOnload()
	    {
	    	PersonInfo personInfo =ContextUtil.getCurrentUserInfo(WafContext.getInstance().getContext()).getPerson();
			HROrgUnitInfo hrOrgInfo= ContextUtil.getCurrentHRUnit(WafContext.getInstance().getContext());

			if(hrOrgInfo!=null)
			{
				isManager = ManagerWebUtil.getManagerPermission(hrOrgInfo,"manager003");					
			}	
			EntityViewInfo entityViewInfo = new EntityViewInfo();
			FilterInfo filterInfo = new FilterInfo();	 
		    if(!isManager)
		    {
			  	filterInfo.getFilterItems().add(new FilterItemInfo("Emp.id",personInfo.getId().toString(),CompareType.EQUALS));		
			  	filterInfo.getFilterItems().add(new FilterItemInfo("HolidayBill.id",null,CompareType.NOTEMPTY));	
			  	filterInfo.getFilterItems().add(new FilterItemInfo("isClose",false,CompareType.EQUALS));	
		    }else
		    {	
				filterInfo.getFilterItems().add(
						new FilterItemInfo("HROrgUnit.longNumber", hrOrgInfo.getLongNumber()+'%', CompareType.LIKE));
			  	filterInfo.getFilterItems().add(new FilterItemInfo("HolidayBill.id",null,CompareType.NOTEMPTY));	
			  	filterInfo.getFilterItems().add(new FilterItemInfo("isClose",false,CompareType.EQUALS));	    	
		    }
		  	filterInfo.setMaskString("#0 and ( #1 or #2)");		
			entityViewInfo.setFilter(filterInfo);
			
			//重新设置查询条件
			setEntityViewInfo(entityViewInfo);
	    }
	    
	    protected void mergeDefaultEntityViewInfo(EntityViewInfo entityViewInfo)
	    {
	    	PersonInfo personInfo =ContextUtil.getCurrentUserInfo(WafContext.getInstance().getContext()).getPerson();
			HROrgUnitInfo hrOrgInfo= ContextUtil.getCurrentHRUnit(WafContext.getInstance().getContext());

			if(hrOrgInfo!=null)
			{
				isManager = ManagerWebUtil.getManagerPermission(hrOrgInfo,"manager003");					
			}	
			FilterInfo filterInfo = new FilterInfo();	 
		    if(isManager)
		    { 
		    	if(StringUtils.isEmpty(entityViewInfo.toString()))
		    	{
					filterInfo.getFilterItems().add(
							new FilterItemInfo("HROrgUnit.longNumber", hrOrgInfo.getLongNumber()+'%', CompareType.LIKE));    
					entityViewInfo.setFilter(filterInfo);
		    	}else
		    	{
			    	try{
						filterInfo.getFilterItems().add(
								new FilterItemInfo("HROrgUnit.longNumber", hrOrgInfo.getLongNumber()+'%', CompareType.LIKE));   
		                this.entityViewInfo.getFilter().mergeFilter(filterInfo, "AND");
			    	}
	                catch(BOSException e)
	                {
	                    logger.warn("merge filter error:", e);
	                }    		
		    	}	
		    }else
		    {
		    	if(StringUtils.isEmpty(entityViewInfo.toString()))
		    	{
				  	filterInfo.getFilterItems().add(new FilterItemInfo("Emp.id",personInfo.getId().toString(),CompareType.EQUALS));	
					entityViewInfo.setFilter(filterInfo);
		    	}else
		    	{
			    	try{
					  	filterInfo.getFilterItems().add(new FilterItemInfo("Emp.id",personInfo.getId().toString(),CompareType.EQUALS));		
		                this.entityViewInfo.getFilter().mergeFilter(filterInfo, "AND");
			    	}
	                catch(BOSException e)
	                {
	                    logger.warn("merge filter error:", e);
	                }    		
		    	}		    	
		    }
	    }
	    
	    private void queryEntityViewInfo()
	    {
	    	PersonInfo personInfo =ContextUtil.getCurrentUserInfo(WafContext.getInstance().getContext()).getPerson();
			PositionInfo positionInfo = getPosition(personInfo);
	    	Date startDate=(Date)pkstartDate.getValue();
	    	Date endDate=(Date)pkendDate.getValue();	
	    	if(startDate==null||endDate==null)
	    	{
	    		
	    	}else
	    	{
				SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
				String startDateStr=myFormatter.format(startDate);
				String endDateStr=myFormatter.format(endDate);
				EntityViewInfo entityViewInfo = new EntityViewInfo();
				FilterInfo filterInfo = new FilterInfo();
				filterInfo.getFilterItems().add(new FilterItemInfo("bizDate",startDateStr,CompareType.GREATER_EQUALS));
			    filterInfo.getFilterItems().add(new FilterItemInfo("bizDate",endDateStr,CompareType.LESS_EQUALS));
			    if(isManager)
			    {
/*			    	dept=(FullOrgUnitInfo)prmtDept.getValue();	    
				    if(dept!=null)
				    {
					  	filterInfo.getFilterItems().add(new FilterItemInfo("hrOrgUnit.id",dept.getId().toString(),CompareType.EQUALS));	
				    }		*/  
					filterInfo.getFilterItems().add(
							new FilterItemInfo("HROrgUnit.longNumber", positionInfo.getHrOrgUnit().getLongNumber()+'%', CompareType.LIKE));
				  	filterInfo.getFilterItems().add(new FilterItemInfo("HolidayBill.id",null,CompareType.NOTEMPTY));	
				  	filterInfo.getFilterItems().add(new FilterItemInfo("isClose",false,CompareType.EQUALS));	
			    }else
			    {
				  	filterInfo.getFilterItems().add(new FilterItemInfo("Emp.id",personInfo.getId().toString(),CompareType.EQUALS));		
				  	filterInfo.getFilterItems().add(new FilterItemInfo("HolidayBill.id",null,CompareType.NOTEMPTY));	
				  	filterInfo.getFilterItems().add(new FilterItemInfo("isClose",false,CompareType.EQUALS));	    	
			    }
			  	filterInfo.setMaskString("#0 and #1 and #2 and (#3 or #4)");	
				entityViewInfo.setFilter(filterInfo);
				
				//重新设置查询条件
				setEntityViewInfo(entityViewInfo);	    		
	    	}
	    }
	    
	    private PositionInfo getPosition(PersonInfo personInfo)
	    {
			PositionInfo positionInfo = null;
			EntityViewInfo entityViewInfo = new EntityViewInfo();
			FilterInfo filterInfo = new FilterInfo();
			filterInfo.getFilterItems().add(
					new FilterItemInfo("person.id", personInfo.getId(),
							CompareType.EQUALS));
			entityViewInfo.setFilter(filterInfo);
			IQueryExecutor iqec = QueryExecutorFactory.getRemoteInstance(new MetaDataPK(    
	                "com.kingdee.eas.custom.aoyuan.aytime.basedata.app",    
	                "PersonHRQuery"));
			try {
				iqec.setObjectView(entityViewInfo);  
				IRowSet irow = iqec.executeQuery();
				if(irow.size()>0)
				{
					if(irow.next())
					{
						 positionInfo=new PositionInfo();
						 HROrgUnitInfo hrOrg=new HROrgUnitInfo();
						 AdminOrgUnitInfo adminOrg=new AdminOrgUnitInfo();
						 String positionId=irow.getString("Position.id");
						 String positionName=irow.getString("Position.name");
						 positionInfo.setId(BOSUuid.read(positionId));
						 positionInfo.setName(positionName);
						 String hrOrgId=irow.getString("HROrgUnit.id");
						 String hrOrgName=irow.getString("HROrgUnit.name");
						 hrOrg.setId(BOSUuid.read(hrOrgId));
						 hrOrg.setName(hrOrgName);
						 hrOrg.setLongNumber(irow.getString("HROrgUnit.longNumber"));
						 String adminOrgId=irow.getString("AdminOrgUnit.id");
						 String adminOrgName=irow.getString("AdminOrgUnit.name");
						 adminOrg.setId(BOSUuid.read(adminOrgId));
						 adminOrg.setName(adminOrgName);
						 positionInfo.setAdminOrgUnit(adminOrg);
						 positionInfo.setHrOrgUnit(hrOrg);
					}
				}
	/*			PositionMemberCollection coll = PositionMemberFactory
						.getRemoteInstance().getPositionMemberCollection(
								entityViewInfo);
				for (int i = 0; i < coll.size(); i++) {
					if (coll.get(i).getPosition() != null) {
						positionInfo = coll.get(i).getPosition();
						if (positionInfo.getAdminOrgUnit() != null) {
							// 找到对应的岗位和行政组织
							break;
						}
					}
				}*/
				return positionInfo;
			} catch (BOSException e) {
				e.printStackTrace();
				return null;
			} catch (SQLException e) {
				e.printStackTrace();
				return null;
			}
	    }    
	    
	    
		public void btnQueryData(){
			try
			{
			    setListModel();				
			}catch (Exception e) {
				e.printStackTrace();
			}
			this.grid.reload();
		}
		
		public void setListModel()throws BOSException, SQLException{
	    	Date startDate=(Date)pkstartDate.getValue();
	    	Date endDate=(Date)pkendDate.getValue();
	    	if(isManager)
	    	{
		    	dept=(FullOrgUnitInfo)prmtDept.getValue();	    		
	    	}
			AbstractBaseObjectCollection coll = getAttenCollection(startDate,endDate,dept);	
			
			if(coll != null){
				for(int n = 0; n < coll.size();n++){
					CoreBaseInfo coreInfo = (CoreBaseInfo) coll.getObject(n);
					Map<String, Object>  listData = CoreInofToMap(coreInfo);
					//if(biilID.contains(listData.get("id").toString()))listData.put("needAudit","y");
					this.listModel.add(listData);
				}
			}
			if(listModel.size()==0)
			{
	    		addMessage("没有找到员工考勤记录!");		
			}
		}
		
		/**
		 * title得到单据信息集合
		 * @return
		 * @throws BOSException 
		 * @throws BOSException 
		 * @throws SQLException 
		 * @throws EASBizException 
		 */
		private AbstractBaseObjectCollection getAttenCollection(Date startDate,Date endDate,FullOrgUnitInfo dept) throws BOSException, SQLException{
			AbstractBaseObjectCollection coll = null;
			
			//请假记录
			//coll=getHoliDayRecord(startDate,endDate,dept);
			
			return coll;
		}
		
		private AbstractBaseObjectCollection getHoliDayRecord(Date startDate,Date endDate,FullOrgUnitInfo dept) throws BOSException
		{
			SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
			String startDateStr=myFormatter.format(startDate);
			String endDateStr=myFormatter.format(endDate);
			AbstractBaseObjectCollection coll = null;
			EntityViewInfo entityViewInfo = new EntityViewInfo();
			FilterInfo filterInfo = new FilterInfo();
			filterInfo.getFilterItems().add(new FilterItemInfo("BizDate",startDateStr,CompareType.GREATER_EQUALS));
		    filterInfo.getFilterItems().add(new FilterItemInfo("BizDate",endDateStr,CompareType.LESS));
		    if(dept!=null)
		    {
			  	filterInfo.getFilterItems().add(new FilterItemInfo("parent.hrOrgUnit.id",dept.getId().toString(),CompareType.EQUALS));	
		    }else{
		    	UserInfo userInfo =ContextUtil.getCurrentUserInfo(WafContext.getInstance().getContext());
			  	filterInfo.getFilterItems().add(new FilterItemInfo("parent.applier.id",userInfo.getId().toString(),CompareType.EQUALS));	    		    	
		    }
			entityViewInfo.setFilter(filterInfo);
			SelectorItemCollection sic = new SelectorItemCollection();
			sic.add("*");
			sic.add(new SelectorItemInfo("holidayType.*"));
			sic.add(new SelectorItemInfo("parent.applier.*"));
			entityViewInfo.setSelector(sic);
			coll=HolidayBillEntryFactory.getRemoteInstance().getCollection(entityViewInfo);
			return coll;			
		}
		
		private Map CoreInofToMap(CoreBaseInfo coreInfo){
			Map map = new HashMap();
			Class coreClass = coreInfo.getClass();
			try {
				Constructor constructor = coreClass.getConstructor();
				Method[] method = coreClass.getMethods();
				for(Method methodinfo:method){
					String methodName = methodinfo.getName();
					if(methodName.startsWith("get") && methodinfo.getGenericParameterTypes().length == 0){
						String pro = methodName.substring(3,4).toLowerCase() + methodName.substring(4);
						Object obj = methodinfo.invoke(coreInfo);
						map.put(pro, obj);
					}
				}
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return map;
		}
		
	    protected String commQueryOptions()
	    {
	       StringBuffer opts = new StringBuffer();
	        opts.append("{");
	        opts.append("PARENT_PAGE_NAME").append(":'");
	        opts.append((new StringBuilder()).append(getClass().getName()).append("',").toString());
	        opts.append("QUERY_NAME").append(":'");
	        opts.append((new StringBuilder()).append(getQueryPK().getFullName()).append("'").toString());
	        String userQuery = getUserQueryView();
	        if(userQuery != null)
	        {
	            opts.append(",");
	            opts.append("USER_QUERY_VIEW").append(":'");
	            opts.append((new StringBuilder()).append(userQuery).append("'").toString());
	        }
	        opts.append("}");
	        return opts.toString();
	    }  	
	    
	    protected void initShowHeight()
	    {
	        Object obj = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("clientHeight");
	        if(obj != null)
	            showHeight = obj.toString();
	        else
	            showHeight = "550";
	        Map params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
	        String objMethod = (String)params.get("fromMethod");
	        int tempHeight = Integer.parseInt(showHeight);
	        if("commonFunctionPortlet".equals(objMethod))
	        {
	            showHeight = String.valueOf(tempHeight - 160);
	            displayRows = (tempHeight - 160 - 53) / 20;
	            if(tempHeight - 160 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        } else
	        if("commonFunctionPortlet".equals(objMethod))
	        {
	            showHeight = String.valueOf(tempHeight - 160);
	            displayRows = (tempHeight - 160 - 53) / 20;
	            if(tempHeight - 160 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        } else
	        if("fastToolbar".equals(objMethod))
	        {
	            showHeight = String.valueOf(tempHeight - 160);
	            displayRows = (tempHeight - 160 - 53) / 20;
	            if(tempHeight - 160 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        } else
	        {
	            showHeight = String.valueOf(tempHeight - 170);
	            displayRows = (tempHeight - 170 - 53) / 20;
	            if(tempHeight - 170 - 53 - displayRows * 20 < 19)
	                displayRows--;
	        }
	    }   
	
	
}

